package com.googlecode.wickedforms.xvergabe.modelers.components;

import java.util.Locale;

import org.xvergabe.xsd.forms.components.x20.Lot;
import org.xvergabe.xsd.forms.components.x20.Lots;
import org.xvergabe.xsd.forms.components.x20.Prequalification;
import org.xvergabe.xsd.forms.components.x20.RoleType;

import com.googlecode.wickedforms.model.SectionModel;
import com.googlecode.wickedforms.model.elements.buttons.AddSectionButtonModel;
import com.googlecode.wickedforms.xvergabe.modelers.XmlModeller;
import com.googlecode.wickedforms.xvergabe.types.ComponentType;
import com.googlecode.wickedforms.xvergabe.util.XMLBeansUtil;

public class LotsModeller implements XmlModeller<Lots, SectionModel> {

	private LotModeller lotModeller = new LotModeller();

	@Override
	public SectionModel createModelFromXml(final Lots xmlObject,
			final Locale locale, final RoleType.Enum displayMode) {

		String title = ComponentType.LOTS.getMessage(locale);
		if (xmlObject.getMetadata() != null) {
			title = XMLBeansUtil.getLabel(xmlObject.getMetadata(), locale);
		}

		SectionModel section = new SectionModel(title);

		for (Lot lot : xmlObject.getLotArray()) {
			section.add(lotModeller
					.createModelFromXml(lot, locale, displayMode));
		}
		
		section.add(new AddSectionButtonModel("weiteres Los") {
			//get the next Lotnumber by incrementing the Lotnumber of the last given lot 
			Integer lotNumber = xmlObject.getLotArray(xmlObject.getLotArray().length-1).getLotNumber().getValue()+1;
			@Override
			public SectionModel createSection() {

				Lot lot = Lot.Factory.newInstance();
				
				lot.set(xmlObject.getLotArray(0));//set uses a copy, not a reference.
				org.xvergabe.xsd.forms.components.x20.Integer lotno = org.xvergabe.xsd.forms.components.x20.Integer.Factory.newInstance();
				
				lotno.setValue(lotNumber++);
				lot.setLotNumber(lotno);
				return lotModeller.createModelFromXml(lot, locale, displayMode);
			}
		});


		return section;
	}

}
